<template>
  <div class="container">
    <el-calendar v-model="currentDate">
      <template #date-cell="{data}">
        <div
            v-if="getSystemDateByDate(data.day) !== undefined"
            class="calendar-cell"
            @click="handleCalendarCellClick(getSystemDateByDate(data.day)!)"
        >
          <div>{{ getDayOfMonth(data.day) }}</div>
          <el-tag v-if="getSystemDateByDate(data.day)!.is_rest === 1" type="primary">休息</el-tag>
        </div>
        <div v-else>{{ getDayOfMonth(data.day) }}</div>
      </template>
    </el-calendar>
  </div>
  <edit-system-date-dialog
      v-model="systemDateToEdit"
      v-model:show="isEditSystemDateDialogShow"
      @success="handleDialogSuccess"
  />
</template>
<script lang="ts" setup>
import {ref, watch} from "vue";
import {getSystemDatesByMonth} from "@/api/systemDate";
import {formatDateToYearAndMonth, getDayOfMonth} from "@/utils/date";
import SystemDateResponse from "@/api/types/systemDate/SystemDateResponse";
import EditSystemDateDialog from "@/components/dialog/EditSystemDateDialog.vue";

const currentDate = ref(new Date())
const systemDates = ref<SystemDateResponse[]>([])
const isLoading = ref(false)
const isEditSystemDateDialogShow = ref(false)
const systemDateToEdit = ref<SystemDateRequest>()

watch(currentDate, (newValue, oldValue) => {
  if (oldValue === undefined || formatDateToYearAndMonth(newValue) !== formatDateToYearAndMonth(oldValue)) {
    getData()
  }
}, {
  immediate: true
})

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true
  }
  const {data} = await getSystemDatesByMonth(formatDateToYearAndMonth(currentDate.value))
  if (data !== undefined) {
    systemDates.value = data
    isLoading.value = false
  }
}

getData()

function getSystemDateByDate(date: string) {
  return systemDates.value.find(systemDate => systemDate.date === date)
}

function handleCalendarCellClick(systemDate: SystemDateResponse) {
  systemDateToEdit.value = {
    date: systemDate.date,
    is_rest: systemDate.is_rest
  }
  isEditSystemDateDialogShow.value = true
}

async function handleDialogSuccess() {
  await getData()
}
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;

  .calendar-cell {
    height: 100%;
  }
}
</style>
